package com.fenghongzhang.module_main.ui.post

import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.fenghongzhang.lib_net.model.Image
import com.fenghongzhang.module_main.R
import com.fenghongzhang.module_main.databinding.LayoutPostItemBinding
import com.fenghongzhang.module_main.glide.pic.Info

class PostPagingAdapter(
    private val onUserClick: ((PostModel) -> Unit)? = null,
    private val onImageClick: ((Int, Int, List<Image>, List<Info>) -> Unit)? = null,
    // 是否显示关系
    private val showAuthorLabel: Boolean = true,
    private val showRelationState: Boolean = true
) : PagingDataAdapter<PostModel, PostViewHolder>(POST_COMPARATOR) {

    private lateinit var mContext: Context
    companion object {
        private val POST_COMPARATOR = object : DiffUtil.ItemCallback<PostModel>() {
            override fun areItemsTheSame(oldItem: PostModel, newItem: PostModel): Boolean =
                oldItem.postsId == newItem.postsId

            override fun areContentsTheSame(oldItem: PostModel, newItem: PostModel): Boolean {
                return oldItem == newItem
            }
        }
    }

    override fun onBindViewHolder(holder: PostViewHolder, position: Int) {
        val binding = DataBindingUtil.getBinding<LayoutPostItemBinding>(holder.itemView)
        val theItem = getItem(position)
        if (theItem != null) {
            theItem.needShowFollowState = showRelationState
            //设置图片
            holder.setMaxLines(2)
            holder.initView(theItem, position)
            binding?.post = theItem
            binding?.holder = holder
            binding?.lFollowState?.isSelected = theItem.hasFollowed()
        }
    }


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PostViewHolder {
        mContext = parent.context
        val binding: LayoutPostItemBinding = DataBindingUtil.inflate(
            LayoutInflater.from(mContext),
            R.layout.layout_post_item,
            parent,
            false
        )

        val postViewHolder = PostViewHolder(
            binding.root,
            onUserClick,
            onImageClick,
        )
        binding.holder = postViewHolder
        binding.showAuthorLabel = showAuthorLabel

        return postViewHolder
    }

}